package com.d09cnpm2.group8;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.d09cnpm2.group8.adapter.ResultListAdapter;
import com.d09cnpm2.group8.dao.TravelDataSource;
import com.d09cnpm2.group8.map.GetDistancesAsyntask;
import com.d09cnpm2.group8.map.ListLocationActivity;
import com.d09cnpm2.group8.map.R;
import com.d09cnpm2.group8.model.TravelLocation;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource.OnLocationChangedListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends Activity implements OnLocationChangedListener {
    private GoogleMap map;
    private LocationManager locationManager;
    String[] distances = { "under 1", "1-5", "5-10", "over 10" };
    private Spinner spinner;
    private ArrayList<TravelLocation> locations;
    private TravelDataSource dataSource;
    private LatLng currentPosition;
    private View searchView;
    private double distanceCritical;
    private String TAG = "----main activity --->";
    private ViewGroup viewGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main_layout);
	viewGroup = (ViewGroup) findViewById(R.id.root);
	Log.e(TAG, viewGroup + "");

	// -------setup map to display current location-----------
	map = ((MapFragment) getFragmentManager().findFragmentById(
		R.id.map_current_location)).getMap();
	displayCurrent();
	dataSource = new TravelDataSource(this);
	dataSource.open();
	spinner = (Spinner) findViewById(R.id.spinner);
	spinner.setAdapter(new ArrayAdapter<String>(this,
		android.R.layout.simple_spinner_dropdown_item, distances));
	// searchView =
    }

    // -------------display a map with current position---------------------
    void displayCurrent() {
	locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
	Criteria criteria = new Criteria();
	String provider = locationManager.getBestProvider(criteria, false);
	Location location = locationManager.getLastKnownLocation(provider);
	currentPosition = new LatLng(location.getLatitude(),
		location.getLongitude());
	map.addMarker(new MarkerOptions().position(currentPosition)
		.title("me here")
		.icon(BitmapDescriptorFactory.fromResource(R.drawable.smile)));
	map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, 15));
	// Zoom in, animating the camera.
	map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
    }

    // -----------view list locations ------------------------
    public void onClick(View view) {
	if (view.getId() == R.id.btn_viewlist) {
	    Intent intent = new Intent(MainActivity.this,
		    ListLocationActivity.class);
	    startActivity(intent);
	} else if (view.getId() == R.id.btn_search) {

	    Toast.makeText(
		    MainActivity.this,
		    "searching places "
			    + distances[spinner.getSelectedItemPosition()],

		    Toast.LENGTH_SHORT).show();
	    distanceCritical = 10;
	    locations = (ArrayList<TravelLocation>) dataSource
		    .getAllLocations();
	    if (locations == null)
		return;
	    GetDistancesAsyntask task = new GetDistancesAsyntask(
		    MainActivity.this, currentPosition);
	    task.execute(locations);
	}
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    // -----------------get list locations with distances-------------------
    public void fetchDistances(ArrayList<String> result) {
	viewGroup.removeAllViews();
	LayoutInflater inflater = (LayoutInflater) this
		.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	View view = inflater.inflate(R.layout.search_view_layout, null);
	viewGroup.addView(view);

	ListView list = (ListView) view.findViewById(R.id.lv_search_result);
	ArrayList<TravelLocation> resultArrayList = locations;
	for (int i = 0; i < result.size(); i++) {
	    String split[] = result.get(i).trim().split(" ");
	    double f = Double.parseDouble(split[0]);
	    if (f < distanceCritical) {
		locations.remove(i);
		result.remove(i);
	    }
	}

	list.setAdapter(new ResultListAdapter(this, resultArrayList, result));
	list.setOnItemClickListener(new OnItemClickListener() {

	    @Override
	    public void onItemClick(AdapterView<?> a, View view, int position,
		    long id) {
		Intent intent = new Intent(MainActivity.this,
			DetailScreen.class);
		TravelLocation obj = locations.get(position);
		Bundle b = new Bundle();
		b.putString("name", obj.name);
		b.putString("desc", obj.descript);
		b.putDouble("lat", obj.lat);
		b.putDouble("lng", obj.lng);
		intent.putExtras(b);
		startActivity(intent);
	    }
	});
    }

    @Override
    public void onBackPressed() {
	// TODO Auto-generated method stub
	super.onBackPressed();
    }

}
